<template>
  <div>
    <slot>
      <el-input v-model="initDisplayData" :readonly="true" :disabled="true" class="tl-ref-selector" :class="{ disabled: disabled }">
        <el-button slot="append" icon="el-icon-search" @click="openDialog" :disabled="disabled"></el-button>
      </el-input>
    </slot>
    <el-dialog :visible.sync="visible" v-dialogDrag :title="title" class="tl-dialog" width="1030px" @open="open" @close="close" top="45px" :append-to-body="true" :modal-append-to-body="true">
      <div style="padding-bottom:10px">
        <!-- 查询界面 -->
        <tl-list-search ref="search" style="margin-top:10px;margin-bottom:10px" :query-param="queryParam" @search="doQuery" :isDisplayDefaultSearch="false">
          <template slot="search">
            <el-form-item label="人员">
              <el-input v-model="queryParam.qry_user" placeholder="请输入工号或姓名"></el-input>
            </el-form-item>
          </template>
        </tl-list-search>
        <!-- 列表界面 -->
        <div>
          <!-- 列表选择 -->
          <div class="table-alert-div" ref="selector">
            <el-alert type="success" :closable="false" class="tl-table-alert-info" effect="light">
              <template slot="title">
                已选择&nbsp;<a class="tl-table-alert-info-a1">{{ selectedRows.length }}</a
                >项&nbsp;&nbsp;
                <a class="tl-table-alert-info-a2" @click="doClearSelected">全部清空</a>
              </template>
            </el-alert>
          </div>
          <!--表格渲染-->
          <el-table class="tl-table" ref="mainTable" :height="tableRefHeight" v-loading="loading" :data="datas" @selection-change="doSelectChange" @sort-change="doSortChange" @row-dblclick="doRowDbClick" row-key="id" border fit :row-class-name="doChangeRowClassName">
            <el-table-column type="selection" :reserve-selection="true" width="55px" v-if="isSingleSelect === false"> </el-table-column>
            <el-table-column prop="username" label="姓名" width="90px" sortable="custom" sort-by="username" align="center" header-align="center"></el-table-column>
            <el-table-column prop="usercode" label="工号" width="90px" sortable="custom" sort-by="usercode" align="center" header-align="center"></el-table-column>
            <el-table-column prop="message" label="工作组名称" width="100px" sortable="custom" sort-by="message" align="center" header-align="center" :show-overflow-tooltip="true"></el-table-column>
            <el-table-column prop="grouprole" label="组内角色" width="90px" sortable="custom" sort-by="grouprole" align="center" header-align="center" :show-overflow-tooltip="true"></el-table-column>
            <el-table-column prop="orgdeptarray" label="公司/部门" :width="deptWidth" sortable="custom" sort-by="orgdeptarray" align="left" header-align="center" :show-overflow-tooltip="true"></el-table-column>
            <el-table-column label="操作" width="80px" align="center" v-if="isSingleSelect === true">
              <template slot-scope="scope">
                <el-button type="text" icon="el-icon-finished" @click="doSelectData(scope.row[fieldKeyComputed])">选择</el-button>
              </template>
            </el-table-column>
          </el-table>
          <!-- 列表分页 -->
          <el-row class="pagebar" ref="pager">
            <el-col :span="10" style="margin-top:13px;margin-left:5px">
              <el-button v-if="!isSingleSelect" type="text" icon="el-icon-user" @click="doSelectedAll">一键选择全部人员</el-button>
              <el-button v-if="!isSingleSelect" type="text" icon="el-icon-delete" class="btn-clear" @click="doClearAllSelected">清空所有选择</el-button>
            </el-col>
            <el-col :span="12">
              <el-pagination :pager-count="5" @size-change="doChangeSize" @current-change="doChangeIndex" :current-page="pageInfo.currentPage" :page-sizes="pageInfo.pageSizes" :total="pageInfo.totalCount" layout="total, sizes, prev, pager, next, jumper" background class="tl-table-pagination"> </el-pagination>
            </el-col>
          </el-row>
        </div>
      </div>
      <div slot="footer" class="dialog-footer" v-if="isSingleSelect === false">
        <el-button type="text" @click="doCancelEdit">取消</el-button>
        <el-button type="primary" @click="doConfirm">确认</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
/** mixins */
import { mixin_ref_list } from '@tapui/mixins/mixin_ref_list'
/** 子组件 */
/** 工具类 */
import { queryDataCode } from '@tapui/api/dataCode'
import { validateNull } from '@tapui/utils/validate'
import { getAction, putAction, postAction } from '@tapui/utils/http'
/** VUE配置 */
export default {
  name: 'tlSdProjectStakeholderRef',
  components: {},
  mixins: [mixin_ref_list],
  data() {
    return {
      description: '项目相关方人员',
      // 默认Key字段名
      fieldDefaultKey: 'usercode',
      // 默认显示字段名
      fieldDefaultValue: 'username', // 用户名
      // url配置
      url: {
        list: '/sd/projectStakeholder/refList'
      },
      // 排序参数
      sorterInfo: {
        sidx: 'messagecode', // 表示工作组
        sord: 'desc'
      },
      // 表示经过初始化的默认值列表
      initSelectedRowKeysArray: []
    }
  },
  props: {
    // 默认显示值
    initDisplayData: {
      default: '',
      type: String
    },
    // v-model绑定值
    value: {
      default: '',
      type: [String, Number]
    }
  },
  computed: {
    tableRefHeight() {
      return this.isSingleSelect ? 380 : 315
    },
    deptWidth() {
      return this.isSingleSelect ? '309px' : '332px'
    }
  },
  methods: {
    /** 关闭 */
    close() {
      // 清空选择、初始化列表，防止再次进入时加载脏数据
      this.initSelectedRowKeysArray = []
      this.doClearSelected()
    },
    /** 查询数据 */
    loadData(paramMap) {
      if (!this.url.list) {
        this.$tap.alert('请设置查询数据地址!')
        return
      }
      // 加载数据 若传入参数1则加载第一页的内容
      if (validateNull(paramMap) === false && Object.keys(paramMap).indexOf('currentPage') > -1) {
        this.pageInfo.currentPage = paramMap['currentPage']
      }
      // 查询条件
      var params = this.getQueryParams()
      this.loading = true
      getAction(this.url.list, params)
        .then((res) => {
          if (res.success) {
            this.datas = res.result.dataList
            this.pageInfo.totalCount = res.result.totalCount
            this.$nextTick(() => {
              if (this.isSingleSelect === false) {
                if (validateNull(this.externalSelectedRowKeys) === false) {
                  // 表示还未进行初始化的数据
                  let externalSelectedRowKeyArray = this.externalSelectedRowKeys.split(',')
                  this.initSelectedRowKeysArray.forEach((selectedKey) => {
                    // 查找已经初始化过的数据，并删除
                    let index = externalSelectedRowKeyArray.findIndex((initKey) => selectedKey === initKey)
                    if (index > -1) {
                      externalSelectedRowKeyArray.splice(index, 1)
                    }
                  })
                  // 当前选中的列表
                  let currentSelectedRowKeys = this.selectedRowKeys
                  this.datas.forEach((item) => {
                    // 表示是否需要初始化该数据
                    let isInitRow = externalSelectedRowKeyArray.includes(item[this.fieldKeyComputed].toString())
                    // 表示该数据是否已被选中
                    let isSelectedRow = currentSelectedRowKeys.includes(item[this.fieldKeyComputed].toString())
                    // 选择：1设定的key不为空、2需要初始化、3未勾选的数据，对其进行勾选操作
                    if (typeof item[this.fieldKeyComputed] !== 'undefined' && isInitRow && !isSelectedRow) {
                      this.$refs.mainTable.toggleRowSelection(item)
                      // 添加到已操作的默认值列表中，用于处理未访问的分页中，未进行勾选的默认值
                      this.initSelectedRowKeysArray.push(item[this.fieldKeyComputed])
                    }
                  })
                }
              }
            })
          } else {
            this.$tap.alert(res.message)
          }
          this.loading = false
        })
        .catch((err) => {
          this.loading = false
        })
    },
    /** 一键选择全部数据 */
    doSelectedAll() {
      if (!this.url.list) {
        this.$tap.alert('请设置查询数据地址!')
        return
      }
      // 查询条件
      let params = this.getQueryParams()
      // 页面大小设为0，以此请求全部数据
      params.pageSize = 0
      this.loading = true
      getAction(this.url.list, params)
        .then((res) => {
          if (res.success) {
            let allDatas = res.result.dataList
            // 当前选中的列表
            let currentSelectedRowKeys = this.selectedRowKeys
            // 刷新页面选择
            allDatas.forEach((item) => {
              // 表示该数据是否已被选中
              let isSelectedRow = currentSelectedRowKeys.includes(item[this.fieldKeyComputed].toString())
              if (typeof item[this.fieldKeyComputed] !== 'undefined' && !isSelectedRow) {
                this.$refs.mainTable.toggleRowSelection(item)
                // 将所有默认值添加到已操作的默认值列表中
                this.initSelectedRowKeysArray = this.externalSelectedRowKeys.split(',')
              }
            })
            // 重新加载该页数据，刷新选项
            this.loadData({})
          } else {
            this.$tap.alert(res.message)
          }
          this.loading = false
        })
        .catch((err) => {
          this.loading = false
        })
    },
    /** 清空全部列表选择 */
    doClearAllSelected(rows) {
      this.selectedRows = []
      this.selectedRowKeys = []
      this.$refs.mainTable.clearSelection()
      this.initSelectedRowKeysArray = this.externalSelectedRowKeys.split(',')
    },
    /** 单选数据 */
    doSelectData(paramKey) {
      this.selectedRows = []
      this.selectedRowKeys = []
      let tempData = this.datas.find((item) => {
        return item[this.fieldKeyComputed] === paramKey
      })
      // TODO 增加tempData空判断
      if (validateNull(tempData)) {
        this.$tap.alert('请选择数据!')
        return
      }
      // 填充数据
      this.selectedRows.push(tempData)
      this.selectedRowKeys.push(tempData[this.fieldKeyComputed])
      // 增加是否单选的判断，避免多选时双击直接关闭窗口
      if (this.isSingleSelect) {
        let selectedValue = tempData[this.fieldValueComputed]
        this.$emit('confirm', this.selectedRows[0], this.selectedRowKeys[0], selectedValue)
        this.visible = false
      }
    },
    /** 多选数据 */
    doConfirm() {
      let selectedValues = ''
      let selectedKeys = ''

      // 外部传入的name和key列表
      if (!validateNull(this.externalSelectedRowKeys) && !validateNull(this.initDisplayData)) {
        let keyArray = this.externalSelectedRowKeys.split(',')
        let nameArray = this.initDisplayData.split(',')
        // 查找未进行初始化的外部数据，重新添加
        keyArray.forEach((key, index) => {
          if (!this.initSelectedRowKeysArray.includes(key)) {
            selectedValues += nameArray[index] + ','
            selectedKeys += key + ','
          }
        })
      }
      // 其余部分未改动
      this.selectedRows.forEach((item) => {
        selectedValues += item[this.fieldValueComputed] + ','
      })
      this.selectedRows.forEach((item) => {
        selectedKeys += item[this.fieldKeyComputed] + ','
      })
      if (selectedValues.length > 0) {
        selectedValues = selectedValues.substring(0, selectedValues.length - 1)
      }
      if (selectedKeys.length > 0) {
        selectedKeys = selectedKeys.substring(0, selectedKeys.length - 1)
      }
      this.$emit('update:initDisplayData', selectedValues)
      this.$emit('input', selectedKeys)
      this.$emit('confirm', this.selectedRows, selectedKeys, selectedValues)
      this.visible = false
    }
  }
}
</script>

<style lang="scss" scoped>
/** “暂无数据”居中显示 */
.tl-table {
  /deep/ .el-table__empty-text {
    text-align: center;
  }
}
/** 表格上边、左边的线 */
.el-table--border,
.el-table--group {
  border: none;
}
/**  表格下边的线 */
.el-table--border::before,
.el-table--group::before {
  width: 0;
}
/**  表格右边的线 */
.el-table--border::after,
.el-table--group::after {
  height: 0;
}
/** 清空选择按钮颜色 */
.btn-clear {
  margin-left: 15px;
  color: #f56c6c;
}
.pagebar /deep/ .el-input__validateIcon {
  display: none;
}
</style>
